package com.xbao.wchat.service;

import com.xbao.wchat.model.TrdSession;
import com.xbao.wchat.model.WxCommon;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * Created by qingshengzheng on 2019/1/25.
 */
@Service
public class WxServiceImpl implements WxService {
    @Value("${wx.appid:xxxx}")
    private String appid;
    @Value("${wx.secret:xxx}")
    private String secret;
    @Value("${wx.grant_type:xx}")
    private String grant_type;
    @Resource
    private ChatCenterService chatCenterService;
    private HashMap<String, String> appMap = new HashMap<String, String>();

    public WxCommon requestWxInfo(String accessToken,String openid) {
        HashMap map = new HashMap();
        map.put("access_token", appid);
        map.put("openid", "openid");
        map.put("lang", "zh_CN");
        try {
            WxCommon common = chatCenterService.getUserInfo(map);
            return common;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public WxCommon getAccessToken(String code) {
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("appid", appid);
        map.put("code", "code");
        map.put("secret", secret);
        map.put("grant_type", grant_type);
        try {
            WxCommon common = chatCenterService.getAccessToken(map);
            return common;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public TrdSession genTrdSession(Long uid, String appkey) {
        TrdSession trdSession = new TrdSession(uid, appkey);
        trdSession.setSessiontime(System.currentTimeMillis());
        String appsec = appkey;
        String v = DigestUtils.md5Hex(uid.toString() + trdSession.getSessiontime().toString() + appsec);
        trdSession.setTstoken(v);
        return trdSession;
    }

    @Override
    public Boolean checkTrdSession(TrdSession session) {
        //验证签名是否合法
        String appsec = session.getAppkey();
        String v = DigestUtils.md5Hex(session.getUid().toString() + session.getSessiontime().toString() + appsec.toString());
        if (v != session.getTstoken())
            return false;
        if (session.getSessiontime() + session.getMaxtime() > System.currentTimeMillis())
            return false;
        return true;

    }

    public ChatCenterService getChatCenterService() {
        return chatCenterService;
    }
}
